var { SuccessModel, ErrorModel } = require('../libs/resmodel');
var { viewrecordAdd, viewrecordUpdate, viewrecordList } = require('../services/viewrecord');
var { init, format } = require('../models/viewrecord');

/**
* 申请访问
* @api {post} /viewrecord/add 申请访问
* @apiDescription 用户申请访问其他人主页，只针对不对外开放的用户
* @apiName add
* @apiParam (参数) {String} pcode 关联员工code
* @apiParam (参数) {String} viewcode 被查看人code
* @apiSampleRequest /viewrecord/add
* @apiGroup viewrecord-申请访问
* @apiVersion 1.0.0
* @apiParamExample {json} Request-Example:
*     {
*       "pcode": "290464549598",
*       "viewcode": "249485919615"
*     }
* @apiSuccessExample {json} Success-Response:
*   HTTP/1.1 200 OK
*   {
*      "msg": "申请成功",
*      "code": 0
*   }
*/
async function add(req, res) {
    let rdata = init(req.body);
    if(rdata.msg){
        res.json(new ErrorModel(rdata.msg));
    }else{
        let result = await viewrecordAdd(rdata.data);
        res.json(result.affectedRows>0 ? new SuccessModel('申请成功', result) : new ErrorModel('申请失败'));
    }
}
/**
* 获取申请列表
* @api {post} /viewrecord/list 获取申请列表
* @apiDescription 获取用户申请查看列表
* @apiName list
* @apiParam (参数) {String} pcode 关联员工code
* @apiSampleRequest /viewrecord/list
* @apiGroup viewrecord-申请访问
* @apiVersion 1.0.0
* @apiParamExample {json} Request-Example:
*     {
*       "pcode": "290464549598",
*     }
* @apiSuccessExample {json} Success-Response:
*   HTTP/1.1 200 OK
*   {
*      "data": [{
*       "pcode": "290464549598", // 申请人code
*       "viewcode": "249485919615", // 被查看人code
*       "commit": "通过", //审批意见
*       "ispass": true, //是否通过
*       "createtime": "2022-04-02 15:23:22", // 申请时间
*       }],
*      "msg": "获取成功",
*      "code": 0
*   }
*/
async function list(req, res) {
    let list = await viewrecordList(req.body);
    res.json(list ? new SuccessModel('获取成功', list) : new ErrorModel('获取失败'));
}

/**
* 处理申请
* @api {post} /viewrecord/audit 处理申请
* @apiDescription 主人授权通过后，访客可查看主页
* @apiName audit
* @apiParam (参数) {String} id 申请记录id
* @apiParam (参数) {Number} ispass 是否通过，1：通过，0: 不通过
* @apiParam (参数) {String} commit 审批意见
* @apiSampleRequest /viewrecord/audit
* @apiGroup viewrecord-申请访问
* @apiVersion 1.0.0
* @apiParamExample {json} Request-Example:
*     {
*       "id": "1",
*       "ispass": true,
*       "commit": "通过"
*     }
* @apiSuccessExample {json} Success-Response:
*   HTTP/1.1 200 OK
*   {
*      "msg": "处理成功",
*      "code": 0
*   }
*/
async function audit(req, res) {
    let rdata = format(req.body);
    if(rdata.msg){
        res.json(new ErrorModel(rdata.msg));
    }else{
        let result = await viewrecordUpdate(rdata.data);
        res.json(result.affectedRows>0 ? new SuccessModel('处理成功', result) : new ErrorModel('处理失败'));
    }
}

module.exports = function (app) {
    let base_url = '/api/viewrecord';

    app.post(base_url+'/add', add);
    app.post(base_url+'/list', list);
    app.post(base_url+'/audit', audit);
}
